package com.han.hotelplat.cms.controller.wallet;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;

import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.ResponseWrapTo;
import com.han.hotelplat.comm.ResponseWrapTo.CodeType;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.AreaHelp;
import com.han.hotelplat.comm.utils.HssfUtil;
import com.han.hotelplat.comm.utils.ListSortUtil;
import com.han.hotelplat.comm.utils.RequestUtil;
import com.han.hotelplat.manager.LogManager;
import com.han.hotelplat.model.AreaModel;
import com.han.hotelplat.model.TaskLogModel;
import com.han.hotelplat.pojo.bill.Bill;
import com.han.hotelplat.pojo.cashextract.CashExtract;
import com.han.hotelplat.pojo.childtask.Childtask;
import com.han.hotelplat.pojo.employee.Employee;
import com.han.hotelplat.pojo.hotel.Hotel;
import com.han.hotelplat.pojo.hotelmanager.Hotelmanager;
import com.han.hotelplat.pojo.log.Logger;
import com.han.hotelplat.pojo.systemuser.Systemuser;
import com.han.hotelplat.pojo.sysuserhotel.SysUserHotel;
import com.han.hotelplat.pojo.task.Task;
import com.han.hotelplat.pojo.wallet.Wallet;
import com.han.hotelplat.service.bill.BillService;
import com.han.hotelplat.service.cashextract.CashExtractService;
import com.han.hotelplat.service.childtask.ChildTaskService;
import com.han.hotelplat.service.hotel.HotelService;
import com.han.hotelplat.service.hotelmanager.HotelmanagerService;
import com.han.hotelplat.service.sysuserhotel.SysUserHotelService;
import com.han.hotelplat.service.task.TaskService;
import com.han.hotelplat.service.wallet.WalletService;

@Controller
@RequestMapping("/cms/wallet")
public class CMSWalletController {
	@Autowired
	private WalletService walletService;
	@Autowired
	private BillService billService;
	@Autowired
	HotelmanagerService hotelmanagerService;
	@Autowired
	private HotelService hotelService;
	@Autowired
	private CashExtractService cashExtractService;
	@Autowired
	private ChildTaskService childTaskService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private LogManager logManager;
	@Autowired
	private SysUserHotelService sysUserHotelService;
	
	@ResponseBody
	@RequestMapping(value = "payOrderTaskForHotel", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET,RequestMethod.POST })
	public String payOrderTaskForHotel(String takid){//对任务划账
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		if(user == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		//Wallet wallet= walletService.getWallet(hotelmanager.getHotelid().longValue());//酒店钱包是用酒店ID作为用户名的
		/*String mypassword = wallet.getPaypassword();
		if(!MD5.toMD5(password).equals(mypassword)){
			return new ResponseWrapTo(-1, "支付密码错误", null).toJson();
		}*/
		Task t = taskService.getHotelTaskDteail(takid);
		if(t.getState().intValue() == Constant.TASK_STATE_STOP.intValue()){
			return  new ResponseWrapTo(-2, "任务已经停止不能继续提交考勤了", null).toJson();
		}
		Map<String, Object> re = childTaskService.paymentChildTaskToEm(takid, 
				t.getHotelid(), user.getUserid(),2, user.getRealname());
		
		int code = (int) re.get("code");
		if(code == 0){
			String host = RequestUtil.getRequest().getRemoteHost();
			Logger logger = new Logger(new Date(), user.getUserid(), host,user.getRealname());
			String context = "确认任务已完成";
			TaskLogModel tlm = new TaskLogModel();
			tlm.setContext(context);
			tlm.setOptcode(Constant.logger.LOG_TASK_FINISH);
			tlm.setTaskid(takid);
			logManager.creatTaskLog(tlm, logger);
		}
		String message = (String) re.get("message");
		return  new ResponseWrapTo(code, message, null).toJson();
	}
	
	/**
	 * 后台确认帮工考勤并将酒店钱转到平台钱包
		 * @description	
		 * @author  han1088
		 * @param childtaskids
		 * @param password
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "payOrder", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET,RequestMethod.POST })
	public String payOrder(String childtaskids, String password, Integer hotelId){//对子任务划账
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		if(user == null){
			return new ResponseWrapTo(CodeType.forbidden, "用户未登录", null).toJson();
		}
		/*Wallet wallet= walletService.getWallet(hotelmanager.getHotelid().longValue());//酒店钱包是用酒店ID作为用户名的
		String mypassword = wallet.getPaypassword();
		if(!MD5.toMD5(password).equals(mypassword)){
			return new ResponseWrapTo(-1, "支付密码错误", null).toJson();
		}*/
		Map<String, Object> re = childTaskService.paymentChildTask(childtaskids, 
				hotelId, user.getUserid(), user.getRealname());
		int code = (int) re.get("code");
		String message = (String) re.get("message");
		return  new ResponseWrapTo(code, message, null).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "expEmpployyerBalance", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET,RequestMethod.POST})
	public void expEmpployyerBalance(HttpServletResponse resp, HttpServletRequest req,String startDate, String endDate
			, Integer areaCode, String condition, Integer sortType){
		List<Employee> data = walletService.expEmpployyerBalance( startDate, endDate, areaCode, condition, sortType);
		String filename = "帮工钱包.xls";
		resp.setHeader("Content-Type", "application/octet-stream");
		DecimalFormat   fnum  =   new  DecimalFormat("##0.00");  
		try {
			resp.setHeader("Content-Disposition", "attachment;filename=" + HssfUtil.buildAttachmentFileName(req, filename));
			List<Object[]> datas = new ArrayList<Object[]>();
			String[] columnNames = new String[] { "姓名","地区","电话","余额"};
			for(Employee em : data){
				Object[] dataObj = new Object[columnNames.length];
				dataObj[0] = em.getRealname();
				String address = "";
				if(em.getArea() != null){
					AreaModel[] area = AreaHelp.getInstance().getAreaModels(em.getArea().toString());
					for(AreaModel a:area){
						address = address+a.getName();
					}
				}
				
				dataObj[1] = address;
				dataObj[2] = em.getTel();
				dataObj[3] = fnum.format(em.getBalance());
				datas.add(dataObj);
			}
			HssfUtil.writeEmBalanceHssf("帮工余额表", columnNames, datas, filename, resp.getOutputStream());
		}catch(Exception e){
			
		}
	}
	
	/**
	 * 
		 * @description	获取酒店列表
		 * @author  han1088
		 * @param startDate起始时间
		 * @param endDate终止时间
		 * @param state状态
		 * @param sortType排序
		 * @param areaCode区域码
		 * @param condition条件
		 * @param pageNo当前页码
		 * @param isArrears是否欠款1是2否
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "expHotelBalance", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET,RequestMethod.POST})
	public void expHotelBalance(HttpServletResponse resp, HttpServletRequest req,String startDate, String endDate,Integer state, Integer sortType
			, Integer areaCode, String condition,Integer isArrears){
		List<Hotel> data = walletService.exportHoteBalance(startDate,  endDate, state,  sortType
				,  areaCode,  condition, isArrears);
		ListSortUtil<Hotel> sort = new ListSortUtil<Hotel>();
		sort.sort(data, "balance", false);
		String filename = "酒店钱包.xls";
		resp.setHeader("Content-Type", "application/octet-stream");
		DecimalFormat   fnum  =   new  DecimalFormat("##0.00");  
		try {
			resp.setHeader("Content-Disposition", "attachment;filename=" + HssfUtil.buildAttachmentFileName(req, filename));
			List<Object[]> datas = new ArrayList<Object[]>();
			String[] columnNames = new String[] { "酒店名称","地区","联系人姓名","联系人电话","余额","授信额度","是否欠费"};
			for(Hotel h : data){
				Object[] dataObj = new Object[columnNames.length];
				dataObj[0] = h.getHotelname();
				String address = "";
				if(h.getArea() != null){
					AreaModel[] area = AreaHelp.getInstance().getAreaModels(h.getArea().toString());
					for(AreaModel a:area){
						address = address+a.getName();
					}
				}
				
				dataObj[1] = address;
				dataObj[2] = h.getRealname();
				dataObj[3] = h.getTel();
				dataObj[4] = dataObj[3] = fnum.format(h.getBalance());
				dataObj[5] = h.getOverdraft();
				if(h.getBalance()<0){
					dataObj[6] = "是";
				}else if(h.getBalance()>=0){
					dataObj[6] = "否";
				}
				datas.add(dataObj);
			}
			HssfUtil.writeHssf("酒店余额表", columnNames, datas, filename, resp.getOutputStream());
		}catch(Exception e){
			
		}
		
	}
	
	@ResponseBody
	@RequestMapping(value = "getWalletBill", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET })
	public String getWalletBill(String userid) {
		List<Bill> data = billService.findMyBill(userid);
		Wallet w = walletService.getWallet(userid);
		Map<String, List<Bill>> billMap = new HashMap<String, List<Bill>>();
		List<Bill>otherBill = new ArrayList<Bill>();
		DecimalFormat   fnum  =   new  DecimalFormat("##0.00");  
		for(Bill bill:data){
			bill.setAmount(Float.parseFloat(fnum.format(bill.getAmount())));
			bill.setBalance(Float.parseFloat(fnum.format(bill.getBalance())));
			if(bill.getType().intValue() == Constant.BILL_TYPE_CASH.intValue()){
				String[] billInfor = bill.getTaskid().split("=");
				Integer state = Integer.parseInt(billInfor[1]);
				bill.setState(state);
			}
			if(bill.getType().intValue() == Constant.BILL_TYPE_TASK.intValue()){
				if(w.getUsertype().equals(Constant.USER_TYPE_EMPLOYEE)){//帮工端需要合并任务类账单
					List<Bill> blist = billMap.get(bill.getTaskid());
					if(blist == null){
						blist = new ArrayList<Bill>();
					}
					blist.add(bill);
					billMap.put(bill.getTaskid(), blist);
				}
				otherBill.add(bill);
			}
		}
		return new ResponseWrapTo(CodeType.success,"数据获取成功",data).toJson();
	}
	
	/**
	 * 
		 * @description	查询钱包余额
		 * @author  han1088
		 * @param userid
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getWalletBalance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String getWalletBalance(String userid){
		Wallet w = walletService.getWallet(userid);
		if(w == null){
			return new ResponseWrapTo(-1, "钱包还未激活！",null).toJson();
		}
		if(w.getUsertype().intValue() == Constant.WALLET_USER_TYPE_HOTEL.intValue()){//酒店钱包
			Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
			String systemUserid = user.getUserid();
			SysUserHotel sh = sysUserHotelService.getBindHotelByUidHid(systemUserid,Integer.parseInt(userid));
			if(sh == null){
				return new ResponseWrapTo(401, "你没有权限查看该酒店的钱包详情", null).toJson();
			}
		}
		w.setPaypassword(null);
		List<Bill> billList = billService.findMyBill(w.getUserid());
		Map<String, List<Bill>> billMap = new HashMap<String, List<Bill>>();
		List<Bill>otherBill = new ArrayList<Bill>();
		DecimalFormat   fnum  =   new  DecimalFormat("##0.00");  
		for(Bill bill:billList){
			bill.setAmount(Float.parseFloat(fnum.format(bill.getAmount())));
			//如果是提现类型的账单
			if(bill.getType().intValue() == Constant.BILL_TYPE_CASH.intValue()){
				String[] billInfor = bill.getTaskid().split("=");
				Integer ceId = Integer.parseInt(billInfor[0]);
				Integer state = Integer.parseInt(billInfor[1]);
				bill.setState(state);
				CashExtract  ce  = cashExtractService.findCashExById(ceId);
				bill.setTaskid(ce.getSerial());
			}
			if(bill.getType().intValue() == Constant.BILL_TYPE_TASK.intValue()){
				if(w.getUsertype().equals(Constant.WALLET_USER_TYPE_EM)){//帮工端需要合并任务类账单
					List<Bill> blist = billMap.get(bill.getTaskid());
					if(blist == null){
						blist = new ArrayList<Bill>();
					}
					blist.add(bill);
					billMap.put(bill.getTaskid(), blist);
				}else{
					otherBill.add(bill);
				}
			}else{
				otherBill.add(bill);
			}
		}
		
		if(billMap.size() != 0){
			billList.clear();
			Iterator<Entry<String, List<Bill>>> billIts = billMap.entrySet().iterator();
			while (billIts.hasNext()) {
				Bill bill = new Bill();
				String optuserid = "";
				String remark = "";
				
				Entry<String, List<Bill>> billEn = billIts.next();
				List<Bill> li = billEn.getValue();
				String taskid = billEn.getKey();
				float amount = 0;
				Date createtime = null;
				int minid = 0;
				float minInbalance = 0;
				for(Bill b : li){
					amount = amount + b.getAmount();
					if(createtime == null || b.getCreatetime().getTime()>createtime.getTime()){
						createtime = b.getCreatetime();
					}
					optuserid = b.getOptuserid();
					remark = b.getRemark();
					if(minid == 0 || minid > b.getId()){//最小入账后前余额
						minid = b.getId();
						minInbalance = b.getInbalance()-b.getAmount();
					}
				}
				bill.setTaskid(taskid);
				bill.setAmount(Float.parseFloat(fnum.format(amount)));
				bill.setCreatetime(createtime);
				bill.setType(Constant.BILL_TYPE_TASK);
				bill.setChargechannel(Constant.CHARGE_CHANNEL_TRANSFER);
				bill.setOptuserid(optuserid);
				bill.setRemark(remark);
				bill.setBalance(Float.parseFloat(fnum.format(minInbalance+amount)));
				billList.add(bill);
			}
			billList.addAll(otherBill);
			ListSortUtil<Bill> sort = new ListSortUtil<Bill>();
			sort.sort(billList, "createtime", false);
		}
		
		w.setBillList(billList);
		return new ResponseWrapTo(CodeType.success, "", w).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @param money
		 * @param walletid 酒店ID
		 * @param remark
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "editHoteBalance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String editHoteBalance(String money, String walletid, String remark){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		if(remark == null || remark.isEmpty()){
			return new ResponseWrapTo(-1, "请填写备注信息", null).toJson();
		}
		Wallet w = walletService.getWallet(walletid);
		if(Float.parseFloat(money)>0){
			billService.creatBill(null, w.getId(), Float.parseFloat(money), 
				Constant.BILL_TYPE_RECHARGE,remark, null, null, Constant.CHARGE_CHANNEL_XX,
				user.getRealname());
		}else if(Float.parseFloat(money)<0){
			billService.creatBill(w.getId(), null, Float.parseFloat(money), 
					Constant.BILL_TYPE_RECHARGE,remark, null, null, Constant.CHARGE_CHANNEL_XX,
					user.getRealname());
		}
		w.setPaypassword(null);
		return new ResponseWrapTo(CodeType.success, "修改酒店余额成功，修改后钱包余额为"+w.getBalance()+money, w).toJson();
	}
	
	
	/**
	 * 
		 * @description	修改帮工钱包余额
		 * @author  han1088
		 * @param balance
		 * @param userid 帮工用户ID
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "editEmBalance", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String editEmBalance(String money, String userid, String remark){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		if(remark == null || remark.isEmpty()){
			return new ResponseWrapTo(-1, "请填写备注信息", null).toJson();
		}
		Wallet w = walletService.getWallet(userid);
		if(w == null){
			return new ResponseWrapTo(-1, "钱包还未创建", null).toJson();
		}
		if(Float.parseFloat(money)>0){
			billService.creatBill(null, w.getId(), Float.parseFloat(money), 
				Constant.BILL_TYPE_RECHARGE,remark, null, null, Constant.CHARGE_CHANNEL_XX,
				user.getRealname());
		}else if(Float.parseFloat(money)<0){
			if((w.getBalance() -(-1*Float.parseFloat(money))<0)){
				return new ResponseWrapTo(-1, "钱包余额不足以扣取", null).toJson();
			}
			billService.creatBill(w.getId(), null, Float.parseFloat(money), 
					Constant.BILL_TYPE_RECHARGE,remark, null, null, Constant.CHARGE_CHANNEL_XX,
					user.getRealname());
		}
		w.setPaypassword(null);
		return new ResponseWrapTo(CodeType.success, "修改帮工钱包余额成功，修改后钱包余额为"+w.getBalance()+money, w).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @param money
		 * @param walletid 酒店ID
		 * @param remark
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "updateHoteOverdraft", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST,RequestMethod.GET })
	public String updateHoteOverdraft(String money, String walletid, String remark){
		Systemuser sysuser = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		Wallet w = walletService.getWallet(walletid);
		if(remark == null || remark.isEmpty()){
			return new ResponseWrapTo(-1, "请填写备注信息", null).toJson();
		}
		//保存并记录修改日志
		walletService.updateHoteOverdraft(Float.parseFloat(money),w,sysuser.getUserid(), remark);
		return new ResponseWrapTo(CodeType.success, "酒店钱包授信额度修改成功充值成功后授信额度为:"+w.getOverdraft(), w).toJson();
	}
	
}
